package httpClient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;

public class FiltPost {
    public static String uploadFile(String uploadUrl, byte[] bbyte,String fileName) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------823928434";
        try {
            URL url = new URL(uploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
     
 
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\""+fileName+"\"" + end);
            dos.writeBytes(end);
            dos.write(bbyte);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();
 
            // 读取服务器返回结果
            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();
//            Log.i("response", "" + result);
            System.out.println(result);
            is.close();
            return  result;
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }	
    public static void main(String[] args) {
    	String url = "http://127.0.0.1:18881/wcs/files";
    	File file = new File("E:\\temp\\ua\\1620706831509GR.jpg");
    	byte[] bbyte = ByteUtil.fileConvertToByteArray(file);
    	uploadFile(url, bbyte, "1620706831509GR.jpg");
	}
}
